import React from 'react'
import { Card, Form, Input, Switch, Button, message, Tabs, Space } from 'antd'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getSystemConfig, updateSystemConfig, reloadConfig } from '../api/gateway'

export default function SystemConfig() {
  const [form] = Form.useForm()
  const queryClient = useQueryClient()

  const { data: config, isLoading } = useQuery({
    queryKey: ['systemConfig'],
    queryFn: getSystemConfig,
  })

  // 当数据加载成功后设置表单值
  React.useEffect(() => {
    if (config) {
      form.setFieldsValue(config)
    }
  }, [config, form])

  const updateMutation = useMutation({
    mutationFn: updateSystemConfig,
    onSuccess: () => {
      message.success('配置更新成功')
      queryClient.invalidateQueries({ queryKey: ['systemConfig'] })
    },
    onError: () => {
      message.error('配置更新失败')
    },
  })

  const reloadMutation = useMutation({
    mutationFn: reloadConfig,
    onSuccess: () => {
      message.success('配置重载成功')
    },
    onError: () => {
      message.error('配置重载失败')
    },
  })

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      updateMutation.mutate(values)
    } catch (error) {
      console.error('Validation failed:', error)
    }
  }

  if (isLoading) {
    return <div>加载中...</div>
  }

  return (
    <div>
      <h1 style={{ marginBottom: '24px' }}>系统配置</h1>
      <Card>
        <Tabs>
          <Tabs.TabPane tab="服务器配置" key="server">
            <Form form={form} layout="vertical" style={{ maxWidth: 600 }}>
              <Form.Item name={['server', 'host']} label="监听地址">
                <Input placeholder="0.0.0.0" />
              </Form.Item>
              <Form.Item name={['server', 'port']} label="端口">
                <Input type="number" placeholder="8080" />
              </Form.Item>
              <Form.Item name={['server', 'mode']} label="运行模式">
                <Input placeholder="debug, release, test" />
              </Form.Item>
            </Form>
          </Tabs.TabPane>
          <Tabs.TabPane tab="CORS 配置" key="cors">
            <Form form={form} layout="vertical" style={{ maxWidth: 600 }}>
              <Form.Item name={['cors', 'enabled']} valuePropName="checked">
                <Switch checkedChildren="启用 CORS" unCheckedChildren="禁用 CORS" />
              </Form.Item>
              <Form.Item name={['cors', 'allow_origins']} label="允许的源">
                <Input.TextArea
                  placeholder="每行一个源，例如：&#10;http://localhost:3000&#10;https://example.com"
                  rows={4}
                />
              </Form.Item>
            </Form>
          </Tabs.TabPane>
          <Tabs.TabPane tab="安全配置" key="security">
            <Form form={form} layout="vertical" style={{ maxWidth: 600 }}>
              <Form.Item name={['security', 'ip_whitelist', 'enabled']} valuePropName="checked">
                <Switch checkedChildren="启用 IP 白名单" unCheckedChildren="禁用 IP 白名单" />
              </Form.Item>
              <Form.Item name={['security', 'ip_whitelist', 'ips']} label="IP 白名单">
                <Input.TextArea
                  placeholder="每行一个 IP，例如：&#10;192.168.1.1&#10;10.0.0.0/8"
                  rows={4}
                />
              </Form.Item>
            </Form>
          </Tabs.TabPane>
        </Tabs>
        <div style={{ marginTop: 16 }}>
          <Space>
            <Button
              type="primary"
              onClick={handleSubmit}
              loading={updateMutation.isLoading}
            >
              保存配置
            </Button>
            <Button
              onClick={() => reloadMutation.mutate()}
              loading={reloadMutation.isLoading}
            >
              热更新配置
            </Button>
          </Space>
        </div>
      </Card>
    </div>
  )
}

